<template>
	<view>
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">新社会单位注册</block>
		</cu-custom>
		<view class="section bg-white padding-sm">
			<u-steps :list="stepList" active-color="#00aaff" mode="number" :current="currentStep"></u-steps>
		</view>
		<view class="section bg-white middle-content">
			<scroll-view :scroll-y="true" :style="bodyHeight">
				<u-form label-width="auto" label-align="right" :model="corpForm" ref="companyForm" v-show="currentStep==0">
					<view class="cu-bar bg-white solid-bottom">
						<view class="action">
							<text class="cuIcon-titles text-orange "></text> 单位信息
						</view>
					</view>
					<u-form-item label="名称" prop="name">
						<u-input v-model="corpForm.name" />
					</u-form-item>
					<u-form-item label="类型" prop="companyType">
						<u-input v-model="corpForm.companyType" type="select" :border="border" @click="showCompanySelect = true" />
						<u-select v-model="showCompanySelect" :list="companyType" @confirm="confirmChooseCompanyType"></u-select>
					</u-form-item>
					<view class="cu-bar bg-white solid-bottom">
						<view class="action">
							<text class="cuIcon-titles text-orange "></text> 法人信息
						</view>
					</view>
					<u-form-item label="名称" prop="legalPerson" :required="true">
						<u-input v-model="corpForm.legalPerson" @focus='nameInputShowHistory=true' @input="nameInputShowHistory=false" />
						<history-input prop="name" :show="nameInputShowHistory" @selected='handleNameSelected'></history-input>
					</u-form-item>
					<u-form-item label="证件类型" prop="identityType" :required="true">
						<u-input v-model="corpForm.identityType" type="select" :border="border" @click="showIdentityTypeSelect = true" />
						<u-select v-model="showIdentityTypeSelect" :list="identityType" @confirm="confirmChooseIdentityType"></u-select>
					</u-form-item>
					<!-- @blur='identityNumberInputShowHistory=false' -->
					<u-form-item label="证件号码" prop="identityNumber" :required="true">
						<u-input v-model="corpForm.identityNumber" @focus='identityNumberInputShowHistory=true' @input="identityNumberInputShowHistory=false"></u-input>
						<history-input prop="identityNumber" :show="identityNumberInputShowHistory" @selected='handleIdentityNumberSelected'></history-input>
					</u-form-item>
					<u-form-item label="手机号" right-icon="phone" prop="phone" :required="true">
						<u-input v-model="corpForm.phone"></u-input>
					</u-form-item>
					<u-form-item label="是否为消防总责任人" :required="true">
						<u-switch slot="right" v-model="corpForm.isFireManager"></u-switch>
					</u-form-item>
				</u-form>

				<u-form label-width="auto" :model="fireForm" ref="fireControlForm" v-show="currentStep==1">
					<view class="cu-bar bg-white solid-bottom">
						<view class="action">
							<text class="cuIcon-titles text-orange "></text> 消防责任人
						</view>
					</view>
					<u-form-item label="姓名" :required="true">
						<u-input v-model="fireForm.manager" />
					</u-form-item>
					<u-form-item label="手机" :required="true">
						<u-input v-model="fireForm.phone" />
					</u-form-item>
					<u-form-item label="证件类型" prop="identityType" :required="true">
						<u-input v-model="fireForm.identityType" type="select" :border="border" @click="showIdentityTypeSelect = true" />
						<u-select v-model="showIdentityTypeSelect" :list="identityType" @confirm="confirmChooseIdentityType"></u-select>
					</u-form-item>
					<u-form-item label="证件号码" required>
						<u-input v-model="fireForm.identityNumber" />
					</u-form-item>
					<u-form-item label="微信" :required="true">
						<u-input v-model="fireForm.wechat" />
					</u-form-item>
				</u-form>
				<u-form label-width="auto" :model="buildingForm" ref="buildingForm" v-show="currentStep==2">
					<view class="cu-bar bg-white solid-bottom">
						<view class="action">
							<text class="cuIcon-titles text-orange "></text> 经营场所
						</view>
						<u-button @click="showAddBusinessPlaceDialog" size="mini">
							<u-icon name="plus"></u-icon>添加经营场所
						</u-button>
					</view>
					<view v-if="!buildingForm.businessPlaces||buildingForm.businessPlaces.length==0">
						<u-empty text="至少添加一处经营场所" mode="list"></u-empty>
					</view>
					<u-swipe-action :show="item.show" :options="options" @click="handleRemoveBuilding" btnWidth="180" :index="index"
					 v-for="(item, index) in buildingForm.businessPlaces" :key="index">
						<u-cell-item icon="map" :title="item.name+item.roomNum" :arrow="true">
							<view class='cu-tag bg-green' v-if="item.isMainAddress">企业住所</view>
						</u-cell-item>
						<view class="fire cu-list menu-avatar card-list  ">
							<view class="cu-item arrow">
								<view class="content">
									<view class="text-pink">
										<view class="text-cut">{{item.name}}</view>
									</view>
									<view class="text-content text-sm flex" v-if="item.buildingNum">
										<view class="text-cut">详细地址：{{item.address}}</view>
									</view>
									<view class="text-content text-sm flex" v-if="item.buildingNum">
										<view class="text-cut">建筑编码：{{item.buildingNum}}</view>
									</view>
									<view class="text-content text-sm flex">
										<view class="text-cut">消防责任人：{{item.manager}}</view>
									</view>
								</view>
							</view>
						</view>
					</u-swipe-action>
				</u-form>
			</scroll-view>
		</view>
		<view class="section bg-white padding-sm fix-bottom" style="display: flex;justify-content: space-between;">

			<template v-if="currentStep>0">
				<u-button @click="prev" style="flex-basis: 20%;">上一步</u-button>
				<u-button v-if="currentStep<2" type="primary" style="flex-basis: 70%;" @click="next">下一步</u-button>
				<u-button v-if="currentStep==2" type="success" @click="submit" style="flex-basis:70%">提交</u-button>
			</template>
			<u-button v-else-if="currentStep==2" type="success" @click="submit" style="flex-basis:100%">提交</u-button>
			<template v-else>
				<u-button type="primary" style="flex-basis:100%;" @click="next">下一步</u-button>
			</template>


		</view>

		<u-popup v-model="buildingForm.addBusinessPlaceDialogVisible" mode="bottom" closeable="true" height="480px"
		 :mask-close-able="false">
			<view style="padding: 20px 5px">
				<scroll-view :scroll-y="true" style="height:410px;">
					<u-form label-width="auto" ref="buildingPopForm">
						<u-form-item :required="true" prop="name" label="所在建筑" placeholder="请选择所在建筑">
							<u-input v-model="buildingForm.addBusinessPlaceForm.businessPlace.name" />
							<u-button size="mini" slot="right" type="success" @click="showMap">打开地图</u-button>
						</u-form-item>
						<u-form-item :required="true" label="详细地址">
							<u-cell-item :arrow="false">{{buildingForm.addBusinessPlaceForm.businessPlace.address}}</u-cell-item>
						</u-form-item>
						<u-form-item label="门牌号">
							<u-input v-model="buildingForm.addBusinessPlaceForm.businessPlace.roomNum" />
						</u-form-item>
						<u-form-item label="建筑编码">
							<u-input v-model="buildingForm.addBusinessPlaceForm.businessPlace.buildingNum" />
						</u-form-item>
						<u-form-item :required="true" label="是否为企业住所">
							<u-switch slot="right" v-model="buildingForm.addBusinessPlaceForm.businessPlace.isMainAddress"></u-switch>
						</u-form-item>
						<u-form-item :required="true" label="消防负责人" prop="manger">
							<u-input v-model="buildingForm.addBusinessPlaceForm.businessPlace.manager" />
						</u-form-item>
						<u-form-item :required="true" label="证件类型" prop="identityType">
							<u-input v-model="buildingForm.addBusinessPlaceForm.businessPlace.identityType" type="select" :border="border"
							 @click="showIdentityTypeSelect = true" />
							<u-select v-model="showIdentityTypeSelect" :list="identityType" @confirm="confirmChooseIdentityType"></u-select>
						</u-form-item>
						<u-form-item :required="true" label="证件号码" prop="identityNumber">
							<u-input v-model="buildingForm.addBusinessPlaceForm.businessPlace.identityNumber"></u-input>
						</u-form-item>
						<u-form-item :required="true" right-icon="phone" label="手机号" prop="phone">
							<u-input v-model="buildingForm.addBusinessPlaceForm.businessPlace.phone"></u-input>
						</u-form-item>
						<u-form-item :required="true" right-icon="weixin-fill" label="微信号" prop="wechat">
							<u-input v-model="buildingForm.addBusinessPlaceForm.businessPlace.wechat"></u-input>
						</u-form-item>
					</u-form>

				</scroll-view>
				<view class="fix-bottom section bg-white padding-sm">
					<u-button @click="addBuilding" type="success">确定</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>
<script>
	import historyInput from '../../components/My/history-input/history-input.vue'
	import {
		companyType,
		identityType
	} from '../../common/dict.js'

	import {
		IDCard
	} from '../../common/regex.js'

	const QQMapWX = require('../../plugin/qqmap-wx-jssdk.js');
	const forms = ["companyForm", "buildingForm", "fireControlForm"];

	export default {
		components: {
			historyInput
		},
		data() {
			return {
				currentStep: 0,
				showCompanySelect: false,
				showIdentityTypeSelect: false,
				companyType: companyType.map(n => ({
					label: n,
					value: n
				})),
				identityType: identityType.map(n => ({
					label: n,
					value: n
				})),
				stepList: [{
					name: '单位信息'
				}, {
					name: '消防信息'
				}, {
					name: '建筑信息'
				}, ],
				corpForm: {
					name: '恒创融慧',
					companyType: "",
					legalPerson: "",
					identityType: "身份证",
					identityNumber: "",
					isFireManager: false,
					phone: ""
				},
				buildingForm: {
					addBusinessPlaceDialogVisible: false,
					addBusinessPlaceForm: {
						businessPlace: {
							address: "", //详细地址
							roomNum: "", //门牌号
							name: "", //建筑名称,
							isMainAddress: false,
							show: false,
							buildingNum: "",
							manager: "",
							identityNumber: "",
							identityType: "身份证",
							address_component: {},
							wechat: "",
							phone: ""
						}
					},
					businessPlaces: []
				},
				fireForm: {
					manager: "",
					identityType: "",
					identityNumber: "",
					isFireManager: "",
					wechat: "",
					phone: ""
				},
				rules1: {
					name: [{
						required: true,
						message: '请输入姓名',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
					}],
					companyType: [{
						required: true,
						message: '请选择单位类型',
						trigger: ['change', 'blur']
					}, ],
					legalPerson: [{
						required: true,
						message: '法人名称必填',
						trigger: ['change', 'blur']
					}],
					phone: [
						// 自定义规则判断是否包含字母"A"

						{
							trigger: ['change', 'blur'],
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: '手机号不合法'
						},
					],
					identityNumber: [{
						trigger: ['change', 'blur'],
						validator: (rule, value, callback) => {
							return this.$u.test.idCard(value);
						},
						message: '证件号码不是有效的身份证'
					}, ]

				},
				rules2: {
					name: [{
						required: true,
						message: '请选择建筑',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
					}],

					manager: [{
						required: true,
						message: '消防负责人名称必填',
						trigger: ['change', 'blur']
					}],
					phone: [
						// 自定义规则判断是否包含字母"A"

						{
							trigger: ['change', 'blur'],
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: '手机号不合法'
						},
					],
					identityNumber: [{
						trigger: ['change', 'blur'],
						validator: (rule, value, callback) => {
							return this.$u.test.idCard(value);
						},
						message: '证件号码不是有效的身份证'
					}, ],
					wechat: [{
						required: true,
						message: '微信号必填',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
					}]

				},
				checkboxList: [{
						name: '苹果',
						checked: false,
						disabled: false
					},
					{
						name: '雪梨',
						checked: false,
						disabled: false
					},
					{
						name: '柠檬',
						checked: false,
						disabled: false
					}
				],
				radioList: [{
						name: '鲜甜',
						disabled: false
					},
					{
						name: '麻辣',
						disabled: false
					}
				],
				radio: '',
				switchVal: false,
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}],
				list: [{
						id: 1,
						title: '长安回望绣成堆，山顶千门次第开，一骑红尘妃子笑，无人知是荔枝来',
						images: 'https://cdn.uviewui.com/uview/common/logo.png',
						show: false
					},
					{
						id: 2,
						title: '新丰绿树起黄埃，数骑渔阳探使回，霓裳一曲千峰上，舞破中原始下来',
						images: 'https://cdn.uviewui.com/uview/common/logo.png',
						show: false
					},
					{
						id: 3,
						title: '登临送目，正故国晚秋，天气初肃。千里澄江似练，翠峰如簇',
						images: 'https://cdn.uviewui.com/uview/common/logo.png',
						show: false,
					}
				],
				nameInputShowHistory: false,
				identityNumberInputShowHistory: false

			};
		},
		computed: {
			// currentForm() {
			// 	return this.$refs[forms[this.currentStep]];
			// }
			bodyHeight() {
				return `max-height:calc(100vh - ${this.CustomBar}px - 72px - 141rpx)`;
			},
			// popVisible(){
			// 	return this.buildingForm.addBusinessPlaceDialogVisible;
			// }
		},
		onReady() {
			this.$refs.companyForm.setRules(this.rules1);
			this.$refs.buildingPopForm.setRules(this.rules2);
			this.corpForm.name = uni.getStorageSync("corpName");
			console.log(this.identityType);
		},
		// watch:{
		// 	popVisible(val){
		// 		if(val){

		// 		}
		// 	}
		// },
		methods: {
			saveContact(data) {
				let contact = uni.getStorageSync("contact");
				const {
					name,
					identityNumber,
					phone,
					wechat
				} = data;
				if (!contact) {
					contact = {
						name: [],
						identityNumber: [],
						phone: [],
						wechat: []
					};
				}
				console.log("identityNumber", identityNumber);
				if (name) {
					contact.name.push(name);
					let set = new Set(contact.name);
					contact.name = Array.from(set);
				}
				if (identityNumber) {
					contact.identityNumber.push(identityNumber);
					let set = new Set(contact.identityNumber);
					contact.identityNumber = Array.from(set);

				}
				if (phone) {
					contact.phone.push(phone.toString());
					let set = new Set(contact.phone);
					contact.phone = Array.from(set);
				}
				if (wechat) {
					contact.wechat.push(wechat.toString());
					let set = new Set(contact.wechat);
					contact.wechat = Array.from(set);
				}

				uni.setStorageSync("contact", contact);
			},
			getContacts() {
				let contact = uni.getStorageSync("contact");
				return contact;
			},
			prev() {
				console.log("prev");
				this.currentStep--;
			},
			next() {
				console.log("next");
				console.log(this.currentStep);
				switch (this.currentStep) {
					case 0:
						{
							// let contact=this.getContacts();

							this.$refs.companyForm.validate(valid => {
								console.log(valid);
								if (valid) {
									if (this.currentStep < this.stepList.length - 1) {
										this.saveContact({
											name: this.corpForm.legalPerson,
											identityNumber: this.corpForm.identityNumber,
											phone: this.corpForm.phone,
										});
										this.currentStep++;
										if (this.corpForm.isFireManager) {
											this.fireForm.manager = this.corpForm.legalPerson;
											this.fireForm.identityNumber = this.corpForm.identityNumber;
											this.fireForm.identityType = this.corpForm.identityType;
											this.fireForm.phone = this.corpForm.phone;

											console.log(this.fireForm);
										}
									}
								}
							});
							break;
						};
					case 1:
						{

							if (this.currentStep < this.stepList.length - 1) {
								this.currentStep++;
							}
							break;
						};
					case 2:
						{
							if (this.currentStep < this.stepList.length - 1) {
								this.currentStep++;
							}
							break;
						};
				}
			},


			submit() {

				let socialUnit = {
					corpName: this.corpForm.name,
					address: this.corpForm.address,
					corpType: this.corpForm.companyType,
					legalPerson: this.corpForm.legalPerson,
					legalPersonIdentityType: this.corpForm.identityType,
					legalPersonIdentityNumber: this.corpForm.identityNumber,
					legalPersonPhone: this.corpForm.phone,
					isFireManager: this.corpForm.isFireManager,
					fireManager: this.fireForm.manager,
					fireManagerIdentityType: this.fireForm.identityType,
					fireManagerIdentityNumber: this.fireForm.identityNumber,
					fireManagerPhone: this.fireForm.phone,
					fireManagerWechat: this.fireForm.wechat,

				}

				let businessPlaces = [];
				businessPlaces = this.buildingForm.businessPlaces.map(n => {
					return {
						corpName: this.corpForm.name,
						address: n.address,
						roomNum: n.roomNum,
						buildingName: n.name,
						province: n.address_component.province,
						city: n.address_component.city,
						area: n.address_component.district,
						street: n.address_component.street,
						fireManager: n.manager,
						identityType: n.identityType,
						identityNumber: n.identityNumber,
						isMainAddress: n.isMainAddress,
						buildingNum: n.buildingNum,
						phone: n.phone,
						wechat: n.wechat

					}
				});
				let postBody = {
					socialUnit,
					businessPlaces
				}
				let optsList = {
					url: 'socialunit/socialunit',
					method: 'post',
				};
				this.$request.httpTokenRequest(optsList, postBody).then(res => {
					console.log(res);
					uni.showToast({
						title: "注册成功",
						icon: "success"
					})
					this.$Router.replace({
						name: "home"
					})
				});
			},
			showMap() {
				uni.chooseLocation({
					success: (res) => {
						console.log(res);
						this.buildingForm.addBusinessPlaceForm.businessPlace.name = res.name;
						this.buildingForm.addBusinessPlaceForm.businessPlace.address = res.address;
						const location = {
							latitude: res.latitude,
							longitude: res.longitude
						};
						var that = this;
						var map = new QQMapWX({
							key: 'NLFBZ-LQC6S-4ZNOR-6K6EN-7IB66-3ABV7'
						})
						console.log(location);
						//通过这个方法来实现经纬度反推省市区
						map.reverseGeocoder({
							location,
							success: (res) => {
								const info = res.result;
								this.buildingForm.addBusinessPlaceForm.businessPlace.address_component = info.address_component;
								console.log(res);
							},
							fail: function(error) {
								console.error(error);
							},

						})

					}

				})
			},
			confirmChooseCompanyType(selected) {
				this.corpForm.companyType = selected[0].value;
			},
			confirmChooseIdentityType(selected) {
				this.corpForm.identityType = selected[0].value;
			},
			showAddBusinessPlaceDialog() {
				this.buildingForm.addBusinessPlaceDialogVisible = true;
			},
			addBuilding() {
				this.$set(this.buildingForm.addBusinessPlaceForm.businessPlace, "show", false);
				this.$set(this.buildingForm.addBusinessPlaceForm.businessPlace, "id", this.$u.guid());
				this.buildingForm.businessPlaces.push(this.buildingForm.addBusinessPlaceForm.businessPlace);
				this.buildingForm.addBusinessPlaceDialogVisible = false;
			},
			handleRemoveBuilding(dataIndex, btnIndex) {
				if (btnIndex == 0) {
					this.buildingForm.businessPlaces.splice(dataIndex, 1);
				}
			},
			inputFocus() {
				this.nameInputShowHistory = true;
			},
			handleIdentityNumberSelected(item) {
				this.corpForm.identityNumber = item;
				this.identityNumberInputShowHistory = false;
			},
			handleNameSelected(e) {
				this.corpForm.legalPerson = e;
				this.nameInputShowHistory = false;
			}
		},
	}
</script>

<style lang="scss">
	.u-form {
		padding: 0 20rpx;
	}
</style>
